import router from "@/router";
import { useUserStoreHook } from "@/store/modules/user";
import { usePermissionStoreHook } from "@/store/modules/permission";
import { useStudyStoreHook } from "@/store/modules/study";
import { useCourseStoreHook } from "@/store/modules/course";
import { useCorrectStoreHook } from "@/store/modules/correct";

import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { setDocumentTitle } from "./utils/title";
NProgress.configure({ showSpinner: false }); // 进度条

const permissionStore = usePermissionStoreHook();
const studyStore = useStudyStoreHook();
const courseStore = useCourseStoreHook();
const correctStore = useCorrectStoreHook();

// 白名单路由
const whiteList = ["/login", "/invite", "/forget", "/register", "/wxlogin"];

const courseList = [
  "/courseinfo",
  "/courseinfo/task",
  "/courseinfo/editask",
  "/courseinfo/addtask",
  "/courseinfo/courseconfig",
  "/courseinfo/authconfig",
  "/courseinfo/students",
  "/courseinfo/class",
  "/courseinfo/rule",
  "/courseinfo/coursematerial",
  "/correctinfo",
  "/correctinfo/correctwork",
  "/correctinfo/statistical",
];

router.beforeEach(async (to, from, next) => {
  // console.log("to.meta.layout", to.meta.layout, to)
  to.meta && typeof to.meta.title !== "undefined" && setDocumentTitle(to);

  NProgress.start();
  const hasToken = localStorage.getItem("accessToken");
  if (hasToken) {
    // console.log("有吗");

    if (to.path === "/login") {
      // 如果已登录，跳转首页
      next({ path: "/" });
      NProgress.done();
    } else {
      if (courseList.indexOf(to.path) !== -1) {
        const hasRoles = courseStore.roles && courseStore.roles.length > 0;
        if (hasRoles) {
          if (to.matched.length === 0) {
            from.name ? next({ name: from.name }) : next("/404");
          } else if (to.meta.layout === "CorrectLayout") {
            if (correctStore.taskName.trim() !== "") {
              if (to.query.experimentId) {
                if (
                  Number(to.query.experimentId) !== correctStore.experimentId ||
                  Number(to.query.courseId) !== courseStore.courseId
                ) {
                  await correctStore.removeCache();
                  await correctStore.resetCorrect();
                  next(`/courseinfo/task?redirect=${to.path}`);
                }
                next();
              } else {
                if (correctStore.experimentId) {
                  const updatedQuery = {
                    ...to.query,
                    experimentId: correctStore.experimentId,
                    courseId: courseStore.courseId,
                  };
                  next({
                    ...to,
                    query: updatedQuery,
                  });
                } else {
                  await correctStore.removeCache();
                  await correctStore.resetCorrect();
                  next(`/courseinfo/task?redirect=${to.path}`);
                  NProgress.done();
                }
              }
            } else {
              try {
                if (to.query.experimentId === undefined) throw "类型参数为空";
                await correctStore.getExpInfo(Number(to.query.experimentId));
                next({ ...to, replace: true });
              } catch (error) {
                // 移除 我学的课程信息 并跳转我学的课 登录页
                await correctStore.removeCache();
                await correctStore.resetCorrect();
                next(`/courseinfo/task?redirect=${to.path}`);
                NProgress.done();
              }
            }
          } else {
            if (to.query.courseId) {
              if (Number(to.query.courseId) !== courseStore.courseId) {
                next(`/course/teach?redirect=${to.path}`);
              } else {
                next();
              }
            } else {
              if (courseStore.courseId) {
                const updatedQuery = {
                  ...to.query,
                  courseId: courseStore.courseId,
                };
                next({
                  ...to,
                  query: updatedQuery,
                });
              } else {
                await courseStore.resetCourse();
                next(`/course/study?redirect=${to.path}`);
                NProgress.done();
              }
            }
          }
        } else {
          try {
            if (to.query.courseId === undefined) throw "类型参数为空";
            await courseStore.teachCourse(Number(to.query.courseId));
            const { roles } = await courseStore.getCourseInfo(
              courseStore.courseId
            );
            const accessRoutes = await permissionStore.generateRoutes(roles);
            accessRoutes.forEach((route) => {
              // console.log("触发第一次");
              router.addRoute(route);
            });
            next({ ...to, replace: true });
          } catch (error) {
            // 移除 token 并跳转登录页
            await courseStore.resetCourse();
            next(`/course/teach?redirect=${to.path}`);
            NProgress.done();
          }
        }
      } else {
        const userStore = useUserStoreHook();
        const hasRoles = userStore.roles && userStore.roles.length > 0;
        if (hasRoles) {
          // 未匹配到任何路由，跳转404
          if (to.matched.length === 0) {
            from.name ? next({ name: from.name }) : next("/404");
          } else {
            if (to.meta.layout === "StudyLayout") {
              if (studyStore.courseName.trim() !== "") {
                if (to.query.courseId) {
                  if (Number(to.query.courseId) !== studyStore.courseId) {
                    await studyStore.removeCache();
                    await studyStore.resetCourse();
                    next(`/course/study?redirect=${to.path}`);
                  }
                  next();
                } else {
                  if (studyStore.courseId) {
                    const updatedQuery = {
                      ...to.query,
                      courseId: studyStore.courseId,
                    };
                    next({
                      ...to,
                      query: updatedQuery,
                    });
                  } else {
                    await studyStore.resetCourse();
                    next(`/course/study?redirect=${to.path}`);
                    NProgress.done();
                  }
                }
              } else {
                try {
                  if (to.query.courseId === undefined) throw "类型参数为空";
                  await studyStore.isValidCourseParams(
                    Number(to.query.courseId)
                  );
                  await studyStore.getCourseInfo();
                  next({ ...to, replace: true });
                } catch (error) {
                  // 移除 我学的课程信息 并跳转我学的课 登录页
                  await studyStore.removeCache();
                  await studyStore.resetCourse();
                  next(`/course/study?redirect=${to.path}`);
                  NProgress.done();
                }
              }
            } else {
              next();
            }
          }
        } else {
          try {
            const { roles } = await userStore.getInfo();
            // console.log("roles", roles);
            const accessRoutes = await permissionStore.generateRoutes(roles);
            // console.log("accessRoutes", accessRoutes);

            accessRoutes.forEach((route) => {
              router.addRoute(route);
            });
            next({ ...to, replace: true });
          } catch (error) {
            // 移除 token 并跳转登录页
            await userStore.resetToken();
            next(`/login?redirect=${to.path}`);
            NProgress.done();
          }
        }
      }
    }
  } else {
    // 未登录可以访问白名单页面
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
